﻿/*
   Copyright 2013 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Flower.Services.Data;
using Assembly = System.Reflection.Assembly;

namespace Flower.SqlServer.Directory.DbGenerator.Generators
{
    internal class GetChildrenProcedure : IGenerator
    {
        private static readonly string GetChildren;
        private static readonly string SpecificJoinedChildrenSelect;
        private static readonly string LimitedChildrenSelect;
        private static readonly Dictionary<SortProperty, string> SortPropertyToColumnMap =
            new Dictionary<SortProperty, string> 
            {
                { SortProperty.Name, "[Name]" },
                { SortProperty.CreatedOn, "[CreatedOn]" },
                { SortProperty.UpdatedOn, "[UpdatedOn]" },
                { SortProperty.Default, "[Id]" },
            };
        private static readonly string[] FilterNameSuffixes = new[] { string.Empty, "Offset", "OffsetLimit" };

        static GetChildrenProcedure()
        {
            Assembly executingAssembly = Assembly.GetExecutingAssembly();

            using (var reader = new StreamReader(executingAssembly.GetManifestResourceStream(Program.ScriptsNamespace + ".GetChildren.sql")))
            {
                GetChildren = reader.ReadToEnd();
            }

            using (var reader = new StreamReader(executingAssembly.GetManifestResourceStream(Program.ScriptsNamespace + ".SpecificJoinedChildrenSelect.sql")))
            {
                SpecificJoinedChildrenSelect = reader.ReadToEnd();
            }

            using (var reader = new StreamReader(executingAssembly.GetManifestResourceStream(Program.ScriptsNamespace + ".LimitedChildrenSelect.sql")))
            {
                LimitedChildrenSelect = reader.ReadToEnd();
            }
        }

        public int Order
        {
            get { return 3; }
        }

        public void Generate(TextWriter writer, Settings settings)
        {
            foreach (EntriesDefinition.EntryDefinition entDef in EntriesDefinition.Entries)
            {
                foreach (SortProperty property in Enum.GetValues(typeof(SortProperty)))
                {
                    foreach (SortOrder order in Enum.GetValues(typeof(SortOrder)))
                    {
                        for (int i = 0; i < 3; i++)
                        {
                            GenerateSingleTypeChildrenSelectProcedure(writer, entDef, property, order, i);
                        }
                    }
                }
            }

            foreach (SortProperty property in Enum.GetValues(typeof(SortProperty)))
            {
                foreach (SortOrder order in Enum.GetValues(typeof(SortOrder)))
                {
                    for (int i = 0; i < 3; i++)
                    {
                        GenerateSingleTypeChildrenSelectProcedure(writer, null, property, order, i);
                    }
                }
            }
        }

        private void GenerateSingleTypeChildrenSelectProcedure(TextWriter writer, EntriesDefinition.EntryDefinition entryDefinition, SortProperty property, SortOrder order, int offsetLimit)
        {
            var specificJoinedSelectBuilder = new StringBuilder(SpecificJoinedChildrenSelect);

            if 
            (
                entryDefinition != null && 
                entryDefinition.SpecificColumns != null && 
                entryDefinition.SpecificColumns.Any(col => !col.Value.DontGenrateInsertUpdate)
            )
            {
                specificJoinedSelectBuilder
                    .Replace
                    (
                        "/*--SpecificColumns--*/",
                        string.Concat
                        (
                            entryDefinition
                                .SpecificColumns
                                .Where(col => !col.Value.DontGenrateInsertUpdate)
                                .Select(col => string.Format("\t[{0}],\n", col.Key))
                        )
                    )
                    .Replace("/*--EntryDataJoin--*/", string.Format("INNER JOIN [{0}] data ON ent.Id = data.DirectoryEntryId", entryDefinition.Name));
            }
            else
            {
                specificJoinedSelectBuilder
                    .Replace("/*--SpecificColumns--*/", string.Empty)
                    .Replace("/*--EntryDataJoin--*/", string.Empty);
            }

            specificJoinedSelectBuilder
                .Replace
                (
                    "/*--EntryType--*/", 
                    (entryDefinition != null) ? 
                        string.Format("AND [Type] = {0}", entryDefinition.DirectoryEntryType) :
                        string.Format("AND [Type] & @Type <> 0")
                )
                .Replace
                (
                    "/*--SortClause--*/", 
                    string.Format
                    (
                        "{0} {1}", 
                        SortPropertyToColumnMap[property], 
                        (order == SortOrder.Asc) ? "ASC" : "DESC"
                    )
                )
                .Replace
                (
                    "/*--OrderByClause--*/", 
                    (offsetLimit == 0) ?
                        string.Format
                        (
                            "ORDER BY {0} {1}", 
                            SortPropertyToColumnMap[property], 
                            (order == SortOrder.Asc) ? "ASC" : "DESC"
                        ) : 
                        string.Empty
                );

            string specificJoinedSelect =
                Helper.Tabify(specificJoinedSelectBuilder.ToString(), "\t");

            if (offsetLimit > 0)
            {
                specificJoinedSelect =
                    Helper.Tabify
                    (
                        new StringBuilder(LimitedChildrenSelect)
                            .Replace("/*--LimitFilter--*/", (offsetLimit == 2) ? "AND N < @Limit" : string.Empty)
                            .Replace("/*--ChildrenSelect--*/", specificJoinedSelect)
                            .ToString(),
                        "\t"
                    );
            }

            var getChildrenBuilder = 
                new StringBuilder(GetChildren)
                    .Replace("/*--Info--*/", (entryDefinition == null) ? "Info" : string.Empty)
                    .Replace("/*--EntryName--*/", (entryDefinition != null) ? entryDefinition.Name : string.Empty)
                    .Replace("/*--Filter--*/", FilterNameSuffixes[offsetLimit])
                    .Replace("/*--Sort--*/", string.Concat(property.ToString(), order.ToString()))
                    .Replace("/*--AdditionalParamsComma-*/", (entryDefinition == null || offsetLimit > 0) ? "," : string.Empty)
                    .Replace("/*--TypeParam--*/", (entryDefinition == null) ? "\t@Type int" + ((offsetLimit > 0) ? "," : string.Empty) : string.Empty)
                    .Replace("/*--OffsetParam--*/", (offsetLimit > 0) ? "\t@Offset bigint" + ((offsetLimit > 1) ? "," : string.Empty) : string.Empty)
                    .Replace("/*--LimitParam--*/", (offsetLimit > 1) ? "\t@Limit bigint" : string.Empty)
                    .Replace("/*--LimitedChildrenSelect--*/", specificJoinedSelect);

            writer.WriteLine(getChildrenBuilder.ToString());
            writer.WriteLine();
        }
    }
}
